<template>
    <div class="field-editor-box">
        <div class="field-editor-toolbar">
            <el-row :gutter="10">


                <el-col :span="1.5">
                    <el-tooltip effect="light" content="添加" placement="top-start">
                        <el-button icon="el-icon-plus" plain circle size="small" @click="inserIndexHandle" />
                    </el-tooltip>
                </el-col>

                <el-col :span="1.5">
                    <el-tooltip effect="light" content="删除" placement="top-start">
                        <el-button icon="el-icon-minus" plain circle size="small" @click="deleteIndexHandle" />
                    </el-tooltip>
                </el-col>


            </el-row>
        </div>
        <vxe-table :data="table.indexs" size="mini" border stripe :keep-source="true" height="100%" ref="xTable"
        :loading="tableLoading"
            class="mytable-scrollbar" :column-config="{ resizable: true }" mouse-config="{area:true}"
            :row-config="{ isHover: true, isCurrent: true }" :keyboard-config="{ isClip: true, isDel: true }"
            :edit-config="{ trigger: 'click', mode: 'row', enabled: true }" :scroll-y="{ enabled: tru }">
            <vxe-column type="seq" width="60"></vxe-column>
            <vxe-column field="name" title="名字" show-header-overflow="title" show-overflow="title" width="200"
                :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                    <vxe-input v-model="row.name" type="text" clearable></vxe-input>
                </template>
            </vxe-column>
            <vxe-column field="indexClo" title="字段" show-header-overflow="title" show-overflow="title" width="200"
                :edit-render="{ autofocus: '.vxe-input--inner' }"><template #edit="{ row }">
                    <vxe-input v-model="row.indexClo" class="my-search"  @clear="indexColNameClearHandle(row)">
                        <template #suffix>
                            <i class="vxe-icon-ellipsis-h" @click="selectFiledClickHandle(row)"></i>
                        </template>
                    </vxe-input>
                </template></vxe-column>
            <vxe-column field="indexType" title="索引类型" show-header-overflow="title" show-overflow="title" width="120"
                :edit-render="{ autofocus: '.vxe-input--inner' }"><template #edit="{ row }">

                    <vxe-select v-model="row.indexType" clearable>
                        <vxe-option v-for="item in indexType" :key="item.value" :value="item.value"
                            :label="item.name"></vxe-option>
                    </vxe-select>
                </template></vxe-column>
            <vxe-column field="indexMethod" title="索引方法" show-header-overflow="title" show-overflow="title" width="120"
                :edit-render="{ autofocus: '.vxe-input--inner' }"><template #edit="{ row }">
                    <vxe-select v-model="row.indexMethod" clearable>
                        <vxe-option v-for="item in indexMethod" :key="item.value" :value="item.value"
                            :label="item.name"></vxe-option>
                    </vxe-select>
                </template></vxe-column>

            <vxe-column field="comment" title="注释" show-header-overflow="title" show-overflow="title" width="300"
                :edit-render="{ autofocus: '.vxe-input--inner' }"><template #edit="{ row }">
                    <vxe-input v-model="row.comment" type="text" clearable></vxe-input>
                </template></vxe-column>
        </vxe-table>
        <el-dialog title="字段信息" v-model="dialogTableVisible">
            <el-row :gutter="10" style="margin-bottom: 10px;">
                <el-col :span="1.5">
                    <el-tooltip effect="light" content="添加" placement="top-start">
                        <el-button icon="el-icon-plus" plain circle size="small" @click="inserIndexColNameHandle" />
                    </el-tooltip>
                </el-col>
                <el-col :span="1.5">
                    <el-tooltip effect="light" content="删除" placement="top-start">
                        <el-button icon="el-icon-minus" plain circle size="small" @click="deleteIndexColNameHandle" />
                    </el-tooltip>
                </el-col>
            </el-row>
            <vxe-table :data="indexColNameList" size="mini" border stripe :keep-source="true" height="300px"
                ref="indexColNameRef" class="mytable-scrollbar" :column-config="{ resizable: true }"
                mouse-config="{area:true}" :row-config="{ isHover: true, isCurrent: true }"
                :keyboard-config="{ isClip: true, isDel: true }"
                :edit-config="{ trigger: 'click', mode: 'row', enabled: true }" :scroll-y="{ enabled: tru }">
                <vxe-column field="name" title="名字" width="150">
                    <template #default="{ row }">
                        <el-select v-model="row.name" size="small" clearable>
                            <el-option v-for="item in table.fields" :key="item.name" :value="item.name"
                                :label="item.name"></el-option>
                        </el-select>
                    </template>
                </vxe-column>
                <vxe-column field="subNum" title="截断数值" width="200">
                    <template #default="{ row }">
                        <el-input-number v-model="row.subNum" size="small" :min="1" controls-position="right" clearable />
                    </template>
                </vxe-column>
                <vxe-column field="sort" title="排序">
                    <template #default="{ row }">
                        <el-select v-model="row.sort" size="small" clearable>
                            <el-option v-for="item in sortType" :key="item.value" :value="item.value"
                                :label="item.name"></el-option>
                        </el-select>
                    </template>
                </vxe-column>
            </vxe-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogTableVisible = false; currIndexColRow = null;indexColNameList=[]">取消</el-button>
                    <el-button type="primary" @click="submitIndexColNameHandle">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>
<script setup>
import { ref, defineProps, nextTick, inject, reactive, watch, defineExpose } from "vue"
import {  indexType, indexMethod, sortType } from "../../service/constant"
import {MetadataService} from "../../service/metadataService"
const props = defineProps({
    connId: {
        type: [String, Number],
        required: true,
        default: undefined
    },
    catalogName: {
        type: String,
        default: undefined
    },
    name: {
        type: String,
        default: undefined
    },
    fields: {
        type: Array
    }
});
const $request = inject('$request');
const $message = inject('$message');
const $messageBox = inject('$messageBox');
const $bus = inject("$bus")
const $keymaster = inject("$keymaster");
const metadataService = new MetadataService($request,$message)
const copyCacheRow = ref("")
const dialogTableVisible = ref(false)
const indexColNameList = ref([])
const indexColNameRef = ref(null)

const table = reactive({
    catalogName: props.catalogName,
    name: props.name,
    fields: [],
    indexs: []
})


const xTable = ref(null);
const createState = ref(true);
const tableLoading = ref(false)

const rowData = ref({});
//更新数据
const updateFieldData = ref([]);
const currRow = ref("")
const currIndexColRow = ref("")



$bus.$on("filedsUpdateKey", (fileds) => {
    table.fields = fileds;
});

watch(
    rowData,
    (newValue, oldValue) => {
        if (newValue._X_ROW_KEY && oldValue._X_ROW_KEY && newValue._X_ROW_KEY === oldValue._X_ROW_KEY) {
            updateFieldData.value.push(newValue)
        }
    },
    { deep: true }
)

const inserIndexHandle = (item) => {
    const row = -1;

    let record = {
        checked: false,
        name: '', type: '', size: null, decimalDigits: null, nullable: true, primaryKey: false, comment: ''
    }
    if (item) {
        record = item;
    }
    table.fields.push(record)
    xTable.value.insertAt(record, row).then(({ rowData }) => {
        xTable.value.setEditRow(rowData)
    })
}

const deleteIndexHandle = () => {
    const row = xTable.value.getCurrentRecord();
    if (!row) {
        $message.warning("请选择一行数据");
        return
    }
    $messageBox.confirm(
        `确定要删除[${row.name}]?`,
        '消息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }
    )
        .then(() => {
            xTable.value.removeCurrentRow()
            return true
        })
        .catch((e) => {
            return true;
        })
}


const getChangeData = () => {
    if (createState.value) {
        return xTable.value.getTableData().fullData;
    }
    let changeFieldData = xTable.value.getRecordset();
    // for (const row of updateFieldData.value) {
    //     if (!changeFieldData.updateRecords.some(item => item._X_ROW_KEY === row._X_ROW_KEY)) {
    //         changeFieldData.updateRecords.push(row)
    //     }
    // }
    return changeFieldData;
}



const getTableIndexs = () => {
    xTable.value&& xTable.value.clearAll();
    tableLoading.value= true;
    metadataService.getTableIndexs(props.connId,table.catalogName, table.name)
    .then(result=>{
        table.indexs = [];
                const groupedBy = {};
                for (const item of result.rows) {
                    if (groupedBy[item.INDEX_NAME]) {
                        groupedBy[item.INDEX_NAME].push(item);
                    } else {
                        groupedBy[item.INDEX_NAME] = [item];
                    }
                }

                for (const row in groupedBy) {
                    table.indexs.push(rowCovert(groupedBy[row]))
                }
    })
    .finally(()=>tableLoading.value = false)
}

const rowCovert = (rows) => {
    const row = rows[0];
    let rowCover = {};
    rowCover.key = row.INDEX_NAME;
    rowCover.name = row.INDEX_NAME;
    const arr = [];

    for (const t of rows) {
        let temp = {};
        temp.name = t.COLUMN_NAME;
        temp.subNum = t.SUB_PART;
        temp.sort = t.COLLATION=='A'?'ASC':'DESC';
        arr.push(temp)
    }
    rowCover.indexColNameList = arr;
    rowCover.indexClo = arr.map(item => buildIndexCol(item)).join(",");
    rowCover.indexType = row.NON_UNIQUE===0?'UNIQUE': indexMethod.some(item=>item.value===row.INDEX_TYPE)?"NORMAL": row.INDEX_TYPE;
    rowCover.indexMethod= row.INDEX_TYPE;
    rowCover.comment = row.INDEX_COMMENT;
    rowCover.oldIndexClo = rowCover.indexClo;
    rowCover.oldIndexType = rowCover.indexType;
    rowCover.oldIndexMethod = rowCover.indexMethod;
    rowCover.oldComment = rowCover.comment;
    return rowCover;

}

//构建索引的字段信息
const buildIndexCol = (row) => {
    return `\`${row.name}\`${row.subNum ? `(${row.subNum})` : ''}  ${row.sort ? row.sort : ''}`
}


const selectFiledClickHandle = (row) => {
    currRow.value = row;
    indexColNameList.value = row.indexColNameList ? row.indexColNameList : [];
    if (indexColNameList.value.length == 0) {
        indexColNameList.value.push({})
    }
    dialogTableVisible.value = true
}
//提交填写的索引字段信息
const submitIndexColNameHandle = () => {
    currRow.value.indexColNameList = indexColNameRef.value.getTableData().fullData;
    currRow.value.indexClo = currRow.value.indexColNameList.map(item => buildIndexCol(item)).join(",")
    indexColNameList.value = []
    dialogTableVisible.value = false
}

//索引字段信息被清除时需要做的操作
const indexColNameClearHandle = (row) => {
    row.indexColNameList = [];
}


//插入数据到字段列表
const inserIndexColNameHandle = async () => {

    const row = -1;

    let record = {
        checked: false,
        name: '', sort: '', subNum: null
    }
    const { row: newRow } = await indexColNameRef.value.insertAt(record, row)
    indexColNameRef.value.setEditRow(newRow)
}

//删除字段信息
const deleteIndexColNameHandle = () => {
    indexColNameRef.value.removeCurrentRow()
}


const init = () => {
    nextTick(() => {
        $keymaster('ctrl+c', () => {

            const row = xTable.value.getCurrentRecord();
            if (!row) {
                return
            }
            copyCacheRow.value = JSON.parse(JSON.stringify(row));
            delete copyCacheRow.value._X_ROW_KEY;
            return true
        });
        $keymaster('ctrl+v', () => {
            if (copyCacheRow.value) {
                const row = xTable.value.getCurrentRecord();
                if (row == null || !xTable.value.isEditByRow(row)) {
                    inserFieldHandle(copyCacheRow.value);
                } else {
                    Object.assign(row, copyCacheRow.value)
                    xTable.value.setCurrentRow(row)
                }

            }
            return true
        });
    })
    //如果表名已经传入，那么就不是新建表，需要从后台拉回表的元数据
    if (table.catalogName && table.name) {
        createState.value = false;
        getTableIndexs();
       
    }

}
init();
//重新刷新组件
const reload = () => {
    init();
}
//设置可访问参数和方法
defineExpose({ reload, getChangeData }) 
</script>

<style lang="scss" scoped>
.field-editor-box {
    height: 100%;
    display: flex;
    flex-direction: column;

    .field-editor-toolbar {
        padding: 0px 5px 5px 5px;
    }

    .other-set-box {
        height: 200px;
        background: #fff;
        border-top: 1px solid #cdcdcd;
        padding: 10px;
    }
}
</style>